package com.zxy.demo.config;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.zxy.demo.service.TaskItemService;

/**
 * Spring容器启动监听器
 * @author ZENG.XIAO.YAN
 * @blog  http://www.cnblogs.com/zeng1994/
 * @version 1.0
 *
 */
@Component
public class StartupListener implements ApplicationListener<ContextRefreshedEvent>{
	/** 这个标识主要用来解决 onApplicationEvent方法被多次调用的问题 */
	private static boolean isRun = false;
	private Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private TaskItemService service;
	
	/** Spring容器启动后，会执行该方法 */
	@Override
	public void onApplicationEvent(ContextRefreshedEvent evt) {
		if(!isRun) {
			try {
				isRun = true;
				log.info("^^^^^^^^-----spring容器启动-------->>>");
				//  开启线程去初始化task,将数据库中的任务添加到quartz中
				//  new Thread(Runnable target, String name)
				Thread t1 = new Thread(() -> {
					// 30秒后初始化
					log.info("============initTask run start");
					try {
						log.info("=========initTask sleep start");
						Thread.sleep(1000 * 30);
						log.info("=========initTask  sleep end");
					} catch (InterruptedException e1) {
						log.info("=========initTask run exception ---> {}", ExceptionUtils.getFullStackTrace(e1));
					}
					service.initTask();
				},"initTaskThread");
				
				t1.start();
			} catch (Exception e) {
				log.error("loading task from db to quartz error, exception -->{}", ExceptionUtils.getFullStackTrace(e));
			}
		}
	}

}
